

$(function () {
    layui.use(['jquery', 'form', 'laytpl', 'laydate', 'element'], function () {
        var $ = layui.jquery, laydate = layui.laydate, laytpl = layui.laytpl, layer = layui.layer;



        let Render = (function () {
            //没有数据模板
            const TEMPLATE_NO_DATA = $("#viewNoDataLayer")[0].innerHTML;
            //区域模板
            const TEMPLATE = $("#viewAreaLayer")[0].innerHTML;
            //结评比模板
            const TEMPLATE_SETTLEMENT_AND_EVALUATE = $("#settlementAndEvaluateLayer")[0].innerHTML;

            const CONTAINER = $('div.layui-container');

            let DataTemplate = {
                date: '2020年12月',
                rows: {
                    num:{
                        title: '人数',
                        cols:{
                            department:{
                                name: '养老机构',
                                value: 0
                            },
                            home:{
                                name: '居家照护',
                                value: 0
                            },
                            evaluate:{
                                name: '评估',
                                value: 0
                            },
                            settlement:{
                                name: '结算',
                                value: 0
                            }
                        },
                        views:[
                            {
                                id: 'view-num-chartOfDepartmentAndHome'
                            },
                            {
                                id: 'view-num-settlementAndEvaluate'
                            }
                        ]
                    },
                    expense:{
                        title: '总费用',
                        cols:{
                            department:{
                                name: '养老机构',
                                value: 0
                            },
                            home:{
                                name: '居家照护',
                                value: 0
                            },
                            evaluate:{
                                name: '评估',
                                value: 0
                            }
                        },
                        views:[
                            {
                                id: 'view-expense-chartOfDepartmentAndHome'
                            }
                        ]
                    },
                    payment:{
                        title: '医保支付',
                        cols:{
                            department:{
                                name: '养老机构',
                                value: 0
                            },
                            home:{
                                name: '居家照护',
                                value: 0
                            },
                            evaluate:{
                                name: '评估',
                                value: 0
                            }
                        },
                        views:[
                            {
                                id: 'view-payment-chartOfDepartmentAndHome'
                            }
                        ]
                    },
                }

            };

            let renderChart = function(setting){
                let chart = echarts.init(setting.dom);
                chart.setOption({
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b}: {c} ({d}%)"
                    },
                    title : {
                        show:true,
                        text: setting.title,//主标题文本，'\n'指定换行
                        x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
                        y: 'bottom',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
                        textStyle: {//主标题文本样式{"fontSize": 18,"fontWeight": "bolder","color": "#333"}
                            fontFamily: 'Arial, Verdana, sans...',
                            fontSize: 14,
                            fontStyle: 'normal',
                            // fontWeight: 'normal',
                        },
                    },
                    series : [
                        {
                            name: setting.name,
                            type: 'pie',
                            radius: '60%',  // 饼图的半径，外半径为可视区尺寸（容器高宽中较小一项）的 55% 长度。
                            data: setting.data,

                        }
                    ]
                })
            };

            let render = function (setting) {
                let data = setting.data;

                if(!data){
                    CONTAINER.children().remove();
                    CONTAINER.append($(TEMPLATE_NO_DATA));
                    return;
                }

                let rows = DataTemplate.rows;
                DataTemplate.date = setting.date;


                //填充数据
                for(let k1 in data){
                    for(let k2 in data[k1]){
                        if(rows[k1]){
                            rows[k1].cols[k2].value = data[k1][k2];
                        }
                    }
                }
                // console.log('DataTemplate', DataTemplate);

                //添加
                let html = laytpl(TEMPLATE).render(DataTemplate);
                // console.log('html', html);
                let dom = $(html);
                CONTAINER.children().remove();
                CONTAINER.append(dom);

                //渲染图标
                //1.人数对比-居家与机构
                renderChart({
                    dom: $('#view-num-chartOfDepartmentAndHome')[0],
                    title: '养老机构-居家照护-人数对比',
                    name: '人数',
                    data:[{name: '养老机构',value: data.num.department }, {name: '居家照护',value: data.num.home }]
                });
                //2.结评比
                $('#view-num-settlementAndEvaluate').append(laytpl(TEMPLATE_SETTLEMENT_AND_EVALUATE).render({
                    value: data.num.evaluate && parseInt(data.num.settlement / data.num.evaluate * 100) + '%'
                }));
                //3.总费用-居家与机构
                renderChart({
                    dom: $('#view-expense-chartOfDepartmentAndHome')[0],
                    title: '养老机构-居家照护-总费用对比',
                    name: '总费用',
                    data:[{name: '养老机构',value: data.expense.department }, {name: '居家照护',value: data.expense.home }]
                });
                //4.医保支付-居家与机构
                renderChart({
                    dom: $('#view-payment-chartOfDepartmentAndHome')[0],
                    title: '养老机构-居家照护-医保支付对比',
                    name: '医保支付',
                    data:[{name: '养老机构',value: data.payment.department }, {name: '居家照护',value: data.payment.home }]
                });

                //重置窗口大小
                window.resizeWindowHeight?window.resizeWindowHeight():'';
            };

            return {
                render: render
            };
        })();

        //拉取数据
        let fetch = function(setting){
            let loadingLayer = layer.load(2, {time: 10*1000});
            $.ajax({
                url: 'selectMonthly',
                data: setting.formData,
                success: (res)=>{
                    if(res.code == 0){
                        let data = res.data[0];

                        /**
                         * 格式化数据
                         * @param field
                         * @return {{num:{}, expense:{}, payment:{}}}
                         */
                        let format = function(data){
                            let formattedData = {};
                            let item;
                            let list;

                            //人数
                            item = {};
                            list = ['department', 'home', 'evaluate', 'settlement'];
                            for(let i in list){
                                item[list[i]] = data['num_' + list[i]];
                            }
                            formattedData.num = item;

                            //费用
                            item = {};
                            list = ['department', 'home', 'evaluate'];
                            for(let i in list){
                                item[list[i]] = data['totfy_' + list[i]];
                            }
                            formattedData.expense = item;

                            //医保支付
                            item = {};
                            list = ['department', 'home', 'evaluate'];
                            for(let i in list){
                                item[list[i]] = data['tczf_' + list[i]];
                            }
                            formattedData.payment = item;

                            // console.log('formattedData', formattedData);
                            return formattedData;

                        };

                        let formattedData;

                        if(data){
                            formattedData = format(data);
                        }
                        if(setting.success){
                            setting.success(formattedData);
                        }
                    }else{
                        if(setting.error){
                            setting.error(res);
                        }
                    }


                },
                error:(res) =>{
                    if(setting.error){
                        setting.error(res);
                    }
                },

                complete: ()=>{
                    layer.close(loadingLayer);
                }
            });
        };


        //初始化表单数据
        let defaultFormData = {
            yearMonth: (function () {
                let now = new Date();
                if(now.getMonth() == 1){
                    return [now.getFullYear()-1, 12].join('-');
                }
                return [now.getFullYear(), now.getMonth() -1].join('-');

            })()
        };
        //测试使用
        // defaultFormData.yearMonth = '2020-12-1';

        //日期(选择日期后直接更新)
        const NOW_DATE = new Date();
        const NOW = [NOW_DATE.getFullYear(), NOW_DATE.getMonth(), NOW_DATE.getDate()].join('-');
        laydate.render({
            elem: '#queryDate',
            type: 'month',
            value: defaultFormData.yearMonth,
            format: 'yyyy-MM',
            isInitValue: true,
            min: '2018-1-1',
            max: NOW,
            theme: 'grid',
            done: function(value){
                fetch({
                    formData: {yearMonth: value},
                    success: (formattedData)=>{
                        //更新
                        Render.render({
                            date: value,
                            data: formattedData
                        })
                    }
                })
            }
        });


        //初始拉取数据
        fetch({
            formData: defaultFormData,
            success: (formattedData)=>{
                //更新
                Render.render({
                    date: defaultFormData.yearMonth,
                    data: formattedData
                })
            },
            error: (res)=>{

                if(res.msg){
                    layer.msg(res.msg, {icon: 2});
                }else if(res.status){
                    layer.msg(res.status, {icon: 2});
                }else{
                    layer.msg('发生了错误', {icon: 2});
                }


            }

        })

    })
});